/*
 * Copyright [2009] [Marcin Rzeźnicki]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mr.go.yaxc.actions;

import java.util.LinkedList;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.xml.sax.Attributes;

/**
 * This action creates a new instance of <i>class</i> using non-default
 * constructor. Used with {@link Create}
 * 
 * <h6>on xml element start:</h6> Obtains <i>property</i> 'class' with a value
 * of <i>class</i> attribute and sets <i>params</i> <h6>on xml element end:</h6>
 * creates instance of <i>class</i> using constructor matching <i>params</i>
 * (see {@link #createInstance(String, Object...)}). If successfull, sets
 * <i>property</i> 'object' <h6>prerequisites:</h6> <i>property</i> 'class' in
 * scope <h6>attributes:</h6> none
 *<p>
 * Example:<br>
 * 
 * <pre>
 * &lt;Create class=&quot;mr.go.yaxc.tests.test2.Something&quot;&gt;
 * 				&lt;Constructor&gt;
 * 					&lt;String&gt;a&lt;/String&gt;
 * 					&lt;Integer&gt;2&lt;/Integer&gt;
 * 				&lt;/Constructor&gt;
 * 			&lt;/Create&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class Constructor extends Action {

    private String classname;

    @Override
    public void carryOut(String name, Attributes attributes,
                         ScopeHandler handler)
            throws Exception {
        classname = (String) handler.getParentProperty("class");
        if (classname == null) {
            throw new ConfigurationError("No class in context");
        }
        params = new LinkedList<Object>();
    }

    @Override
    public void processed(String body, ScopeHandler handler)
            throws Exception {
        final Object o = createInstance(classname,
                                        params.toArray());
        handler.setParentProperty("object",
                                  o);
    }
}
